package com.gitee.wsl.coroutines.strategy

import com.gitee.wsl.ext.reflect.SuspendVoidFunction
import com.gitee.wsl.ext.reflect.TParams
import com.gitee.wsl.ext.reflect.VoidFunction
import kotlinx.coroutines.CoroutineScope

interface RequestState{

    fun request():Boolean

    fun reset()

}

class BooleanState(var singleLocked:Boolean = false):RequestState{
    override fun request(): Boolean{
        if(!singleLocked){
            singleLocked = true
            return true
        }
        return false
    }

    override fun reset() {
        singleLocked = false
    }

}

fun request(s:RequestState = BooleanState(), fn: VoidFunction):VoidFunction{
    return object:VoidFunction{
        override fun invoke(p1: TParams) {
            if(!s.request()) return
            try {
                fn.invoke(p1)
            }finally {
                s.reset()
            }
        }
    }
}

fun CoroutineScope.request(s:RequestState = BooleanState(), fn: SuspendVoidFunction):SuspendVoidFunction{
    return object:SuspendVoidFunction{
        override suspend fun invoke(p1: TParams) {
            if(!s.request()) return
            try {
                fn.invoke(p1)
            }finally {
                s.reset()
            }
        }
    }
}